package com.caidan.diagram.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 全局异常拦截器
 *
 * 该类通过 @ControllerAdvice 注解，拦截全局 Controller 抛出的异常，
 * 并根据不同异常类型返回相应的响应信息和状态码。
 */
@ControllerAdvice
public class GlobalExceptionHandler {

    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 处理自定义的 RiskException 异常
     *
     * @param ex RiskException 对象
     * @return 包含错误码和错误信息的响应实体
     */
//    @ExceptionHandler(RiskException.class)
//    @ResponseBody
//    public ResponseEntity<ErrorResponse> handleRiskException(RiskException ex) {
//        logger.error("RiskException occurred: ", ex);
//
//        String errorMessage = ex.getMessage();
////        判断等级，然后练习管理员。
//        ErrorResponse errorResponse = new ErrorResponse();
//        errorResponse.setCode(HttpStatus.BAD_REQUEST.value());
//        errorResponse.setMessage(ex.getMessage());
//        return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
//    }

    /**
     * 处理所有其他异常
     *
     * @param ex Exception 对象
     * @return 包含错误码和错误信息的响应实体
     */
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public ResponseEntity<ErrorResponse> handleGeneralException(Exception ex) {
        logger.error("Exception occurred: ", ex);
        ErrorResponse errorResponse = new ErrorResponse();
        errorResponse.setCode(HttpStatus.INTERNAL_SERVER_ERROR.value());
        errorResponse.setMessage("服务器内部错误，请稍后重试");
        return new ResponseEntity<>(errorResponse, HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

/**
 * 错误响应实体，用于统一返回错误信息
 */
class ErrorResponse {
    private int code;
    private String message;

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }
}
